package dk.modified.radioonlineapp;

import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class SplashScreen extends Activity {

	private CommentsDataSource datasource;
	public static ProgressBar mProgress;
	private TextView splashText;
	public static int mProgressStatus = 0;
	private static String radioLanguage;
//	private ImageView splashLogo;

//	@Override
//	protected void onDestroy() {
//		// TODO Auto-generated method stub
//		super.onDestroy();
//		datasource = null;
//		list = null;
//		splashText = null;
//		mProgress = null;
//		radioLanguage = null;
//		splashLogo.setBackgroundDrawable(null);
//		splashLogo.setImageDrawable(null);
//		splashLogo = null;
//		System.gc();
//	}
//	
//	
//	@Override
//	protected void onPause() {
//		// TODO Auto-generated method stub
//		super.onPause();
//		System.gc();
//	}
//
//
//	@Override
//	protected void onResume() {
//		// TODO Auto-generated method stub
//		super.onResume();
//		System.gc();
//	}


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// Read settings on startup.
		String language = getPhoneLanguage();
		PreferenceManager.setDefaultValues(this, R.xml.settings, false);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		radioLanguage = prefs.getString("app_location", language);
		String applicationLanguage = prefs.getString("app_language", language);
		changeLanguage(applicationLanguage);
		setContentView(R.layout.splashscreen);
//		splashLogo = (ImageVi	ew) findViewById(R.id.imageView1);
		
		// If an Internet connection is available, a fresh JSONParser is prepared to update values and initiate later needed views.
		// if no internet connection is available, a message is shown, informing the user of the problem and provide a one click shortcut to android connection settings.
		if (haveNetworkConnection()) {
			mProgress = (ProgressBar) findViewById(R.id.progressBar);
			splashText = (TextView) findViewById(R.id.splashText);
			//Get data by local language
			JSONparser.getRadios(
					"https://itunedradio.com/app_access/json_parser.php?lang="
							+ radioLanguage + "&limit=1", true);
			
			JSONparser.clearStuff();
			
			//If no data for local language, so get data from English stations
			if (JSONparser.country == null) {
				radioLanguage = "EN";
				
				int tryingtime = 0;
				// Try loading data until getting data from server
				while (JSONparser.country == null && tryingtime < 10) {
					// Get number of station?
					JSONparser.getRadios(
						"https://itunedradio.com/app_access/json_parser.php?lang="
								+ radioLanguage + "&limit=1", true);
					
					tryingtime++;
				}
				JSONparser.clearStuff();
			}

			int count = JSONparser.number;
			mProgress.setMax(count + count + 15);
			new AsyncSplash().execute();
		} else {
			new AlertDialog.Builder(this)
					.setCancelable(false)
					.setTitle(getString(R.string.no_network_detected))
					.setMessage(getString(R.string.enable_network_to_proceed))
					.setPositiveButton(getString(R.string.close_app),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							})
					.setNegativeButton(getString(R.string.navigate_to_wifi),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									startActivity(new Intent(
											WifiManager.ACTION_PICK_WIFI_NETWORK));
								}
							}).show();
		}

	}
	


	// Set the language of the app to the received string value
	private void changeLanguage(String lang){
		Locale locale = new Locale(lang); 
		Locale.setDefault(locale);
		Configuration config = new Configuration();
		config.locale = locale;
		getApplicationContext().getResources().updateConfiguration(config, null);
	}
	
	// Returns the language that te Android OS is set to.
	private String getPhoneLanguage() {
		String language;
		language = Locale.getDefault().getLanguage();
		language = language.toUpperCase();
		language = language.substring(0, 2);
		return language;
	}
	
	// Deletes all .png files saved by the app.
	private void deleteFiles() {
		String[] arr = fileList();
		for (int i = 0; i < arr.length; i++) {
			if (arr[i].contains(".png")) {
				deleteFile(arr[i]);
			}
		}
	}
	
	// Goes to the MainActivity.
	public void startMain() {
		Intent i = new Intent(SplashScreen.this, MainActivity.class);
		startActivity(i);
	}
	
	// Sees if a Internet connection is available.
	private boolean haveNetworkConnection() {
		boolean haveConnectedWifi = false;
		boolean haveConnectedMobile = false;

		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		for (NetworkInfo ni : netInfo) {
			if (ni.getTypeName().equalsIgnoreCase("WIFI"))
				if (ni.isConnected())
					haveConnectedWifi = true;
			if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
				if (ni.isConnected())
					haveConnectedMobile = true;
		}
		return haveConnectedWifi || haveConnectedMobile;
	}
	
	// Tasks run on startup.
	public class AsyncSplash extends AsyncTask<Void, Integer, Void> {
		
		// When doInBackground is done, moves on the the main activity.
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			startMain();
		}
		
		// Before doInBackground, checks up on database version and if any previous user data exists.
		// If database version is older than new version, shows progress bar and text.
		@Override
		protected void onPreExecute() {

			datasource = new CommentsDataSource(SplashScreen.this);
			datasource.Open();
			Log.d("USE FULL INFO!", "Database: " + datasource.GetCountry()
					+ " JSON: " + JSONparser.country + " Local: "
					+ radioLanguage);
			Log.d("Version", String.valueOf(JSONparser.version));

			//Bug fix: JSONparser.country is probably null (get error when using equals)
			if (JSONparser.version > datasource.GetVersion()
					|| JSONparser.country != datasource.GetCountry()) {

				mProgress.setVisibility(View.VISIBLE);
				splashText.setVisibility(View.VISIBLE);
			}

			if (!datasource.DoesEntryOfUserDataExist()) {
				if (JSONparser.country != null) {
					datasource.InsertIntouserData(0, 0, JSONparser.country);
				} else {
					datasource.InsertIntouserData(0, 0, radioLanguage);
				}
			}
			datasource.Close();
		}
		
		// Keeps the progress bar updated at all times.
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			mProgress.setProgress(values[0]);
		}
		
		// If database is older than new version, gets the new one and overwrites the old one.
		// This is of course based on preferred country.
		// Will update lists in main activity, used in the ListViews.
		@Override
		protected Void doInBackground(Void... arg0) {

			datasource.Open();
			Log.d("USE FULL INFO!", "Database: " + datasource.GetCountry()
					+ " JSON: " + JSONparser.country + " Local: "
					+ radioLanguage);
			Log.d("Version", String.valueOf(JSONparser.version));

			if (JSONparser.version > datasource.GetVersion()
					|| !JSONparser.country.equals(datasource.GetCountry())) {
				deleteFiles();
				mProgressStatus = 5;
				publishProgress(mProgressStatus);
				datasource.UpdateVersion();
				datasource.UpdateCountry();
				mProgressStatus = 10;
				publishProgress(mProgressStatus);
				datasource.DeleteDB();
				mProgressStatus = 15;
				publishProgress(mProgressStatus);
				
				List<Radio> list = null;
				
				int tryingtime = 0;
				// Try loading data until getting data from server
				while (list == null && tryingtime < 10) {
					list = JSONparser.getRadios(
							"https://itunedradio.com/app_access/json_parser.php?lang="
									+ radioLanguage + "&limit=999999", true);
					tryingtime++;
				}
				
				for (int i = 0; i < list.size(); i++) {
					try {
						datasource.InsertRadioFromJSON(list.get(i));
					} catch (Exception e) {
						e.printStackTrace();
					}
					publishProgress(i + JSONparser.number + 15);
				}
			}

			try {
			  MainActivity.listRa = datasource.SelectRadiosFromDB();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				MainActivity.listRaMost = datasource.SelectMostRadiosFromDB();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				MainActivity.listRaFav = datasource.SelectFavRadiosFromDB();
			} catch (Exception e) {
				e.printStackTrace();
			}
			datasource.Close();
			return null;
		}
	}
}